﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.ServiceModel;
using System.IO;

namespace BLL.SystemInformation
{
    [ServiceContract]
    class UC_StaffInformation
    {
        //实例化数据层
        DAL.DALMethod myDAL = new DAL.DALMethod();
        //指示方法定义一个操作协定
        [OperationContract]
        public DataSet SelectAllStaff()
        {
            //声明对象数组
            SqlParameter[] parm =
            {
                new SqlParameter("@type",SqlDbType.VarChar),
            };
            //给对象数组赋值
            parm[0].Value = "UserControl_Loaded_SelectStaff";
            //查询数据缓存
            return myDAL.QueryDataSet("UCStaffInformation", parm);
        }
        #region 图片处理
        //根据图片名称查找图片路径
        [OperationContract]
        public string SelectPhoro(string strFileName)
        {
            try
            {
                string strPhotoLuJing = null;
                if (strFileName != null)
                {
                    //得到服务端所在位置的应用程序集（基目录）
                    string strSaveLuJing = AppDomain.CurrentDomain.BaseDirectory;
                    //获取图片路径（基目录+文件夹+文件名称）
                    string strPath = strSaveLuJing + "image\\" + strFileName;
                    if (strPath != "")
                    {
                        //找到文件
                        strPhotoLuJing = strPath;
                    }
                    else
                    {
                        //找不到文件
                        strPhotoLuJing = null;
                    }
                }

                return strPhotoLuJing;
            }
            catch (Exception)
            {
                return null;
            }
        }
        #endregion
        #region 绑定下拉框
        /// <summary>
        /// 查询性别
        /// </summary>
        /// <returns></returns>
        [OperationContract]
        public DataSet SelectGender()
        {
            SqlParameter[] parm =
            {
                new SqlParameter("@type",SqlDbType.VarChar)
            };
            parm[0].Value = "InsertStaffInformation_Loaded_SelectGender";           
            return myDAL.QueryDataSet("UCStaffInformation", parm);
        }
        /// <summary>
        /// 查询工作状态
        /// </summary>
        [OperationContract]
        public DataSet SelectWorkStatus()
        {
            SqlParameter[] parm =
            {
                new SqlParameter("@type",SqlDbType.VarChar)
            };
            parm[0].Value = "InsertStaffInformation_Loaded_SelectWorkStatus";
            return myDAL.QueryDataSet("UCStaffInformation", parm);
        }
        /// <summary>
        /// 查询员工类型
        /// </summary>
        /// <returns></returns>
        [OperationContract]
        public DataSet SelectEmployeeType(int intfid)
        {
            SqlParameter[] parm =
            {
                new SqlParameter("@type",SqlDbType.VarChar),
                new  SqlParameter ("@fid",SqlDbType.Int),
            };
            parm[0].Value = "UserControl_Loaded_SelectEmployeeType";
            parm[1].Value = intfid;
            return myDAL.QueryDataSet("UCStaffInformation", parm);
        }
        [OperationContract] //查询职务
        public DataSet SelectPost()

        {
            SqlParameter[] SQLCMDpas ={
                                     new  SqlParameter ("@Type",SqlDbType.Char),

                                           };
            SQLCMDpas[0].Value = "InsertStaffInformation_Loaded_SelectPost";
            return myDAL.QueryDataSet("UCStaffInformation", SQLCMDpas);
        }

        #endregion
        /// <summary>
        /// 新增员工信息
        /// <returns></returns>
        [OperationContract]
        public int InsertStaffInformation(int as_EmployeeTypeID, int as_WorkStatusID, int as_BranchID, string staffName, string staffNumber, int as_GenderID, string staffAge, string idCard,DateTime dateOfBirth, string phoneNumber, string staffAddress, string eMail, DateTime entryDate, DateTime departureDate,bool  operatorOrNot, byte[][]staffPicture, string note)
        {
            //声明变量接收=>文件名字
            string strPatientPhotos = WenJianLiuZhuanHuanLuJing(staffPicture);
            SqlParameter[] parm =
            {
                new SqlParameter("@type",SqlDbType.VarChar),
                new SqlParameter("@as_EmployeeTypeID",SqlDbType.Int),
                new SqlParameter("@as_WorkStatusID",SqlDbType.Int),
                new SqlParameter("@as_BranchID",SqlDbType.Int),
                new SqlParameter("@staffName",SqlDbType.VarChar),
                new SqlParameter("@staffNumber",SqlDbType.VarChar),
                new SqlParameter("@as_GenderID",SqlDbType.Int),
                new SqlParameter("@staffAge",SqlDbType.VarChar),
                new SqlParameter("@idCard",SqlDbType.VarChar),
                new SqlParameter("@dateOfBirth",SqlDbType.DateTime),
                new SqlParameter("@phoneNumber",SqlDbType.VarChar),
                new SqlParameter("@staffAddress",SqlDbType.VarChar),
                new SqlParameter("@eMail",SqlDbType.VarChar),
                new SqlParameter("@entryDate",SqlDbType.DateTime),
                new SqlParameter("@departureDate",SqlDbType.DateTime),
                new SqlParameter("@operatorOrNot",SqlDbType.Bit),
                new SqlParameter("@staffPicture",SqlDbType.VarChar),
                new SqlParameter("@note",SqlDbType.VarChar)
            };
            parm[0].Value = "btn_Affirm_Click_InsertStaff";
            parm[1].Value = as_EmployeeTypeID;
            parm[2].Value = as_WorkStatusID;
            parm[3].Value = as_BranchID;
            parm[4].Value = staffName;
            parm[5].Value = staffNumber;
            parm[6].Value = as_GenderID;
            parm[7].Value = staffAge;
            parm[8].Value = idCard;
            parm[9].Value = dateOfBirth;
            parm[10].Value = phoneNumber;
            parm[11].Value = staffAddress;
            parm[12].Value = eMail;
            parm[13].Value = entryDate;
            parm[14].Value = departureDate;
            parm[15].Value = operatorOrNot;
            parm[16].Value = strPatientPhotos;
            parm[17].Value = note;
            int count = myDAL.UpdateData("UCStaffInformation", parm);
            return count;
        }
        /// <summary>
        /// 文件流转换路径
        /// </summary>
        /// <param name="byteTuPian"></param>
        /// <returns></returns>
        [OperationContract]
        private string WenJianLiuZhuanHuanLuJing(byte[][] byteTuPian)
        {
            try
            {
                string strBaoCunLuJing;
                //获取基目录，它由程序集冲突解决程序用来探测程序集。
                string strPath = System.AppDomain.CurrentDomain.BaseDirectory + "image\\";
                //第一步：判断文件夹image
                if (!Directory.Exists(strPath))
                {
                    //文件夹不存在：创建文件夹
                    Directory.CreateDirectory(strPath);
                }
                //拼接日期
                string strWenJianQianZui = DateTime.Now.ToString("yyyyMMddHHmmssffff");
                string strWenJianName = "";
                //遍历二进制的数组的数组
                for (int i = 0; i < byteTuPian.Length; i++)
                {
                    //文件命名：日期+后缀
                    string strRiQiWenJian = strWenJianQianZui + i.ToString() + ".png";
                    //拼接路径(创建的路径+文件名)
                    strBaoCunLuJing = strPath + strRiQiWenJian;
                    FileInfo fi = new FileInfo(strBaoCunLuJing);
                    FileStream fs;
                    // 创建只写 System.IO.FileStream。
                    fs = fi.OpenWrite();
                    //将字节块写入文件流。(数组，开始字节索引，长度)
                    fs.Write(byteTuPian[i], 0, byteTuPian[i].Length);
                    //关闭当前流并释放与之关联的所有资源
                    fs.Close();
                    strWenJianName = strRiQiWenJian;
                }
                //返回文件名字
                return strWenJianName;
            }
            catch (Exception)
            {
                return null;
            }
        }
        /// <summary>
        /// 修改员工信息
        /// <returns></returns>
        [OperationContract]
        public int UpdateStaffInformation(int as_EmployeeTypeID, int as_WorkStatusID, int as_BranchID
            , string staffName, string staffNumber, int as_GenderID, string staffAge
            , string idCard, DateTime dateOfBirth, string phoneNumber, string staffAddress
            , string eMail, DateTime entryDate, DateTime departureDate
            , bool operatorOrNot, byte[][] staffPicture, string note,int staffID
            ,string strOldLuJing,string strTxtLuJing)
        {
            //声明变量接收=>文件名字
            string strPatientPhotos = UWenJianLiuZhuanHuanLuJing(staffPicture, strOldLuJing, strTxtLuJing);
            SqlParameter[] parm =
            {
                new SqlParameter("@type",SqlDbType.VarChar),
                new SqlParameter("@as_EmployeeTypeID",SqlDbType.Int),
                new SqlParameter("@as_WorkStatusID",SqlDbType.Int),
                new SqlParameter("@as_BranchID",SqlDbType.Int),
                new SqlParameter("@staffName",SqlDbType.VarChar),
                new SqlParameter("@staffNumber",SqlDbType.VarChar),
                new SqlParameter("@as_GenderID",SqlDbType.Int),
                new SqlParameter("@staffAge",SqlDbType.VarChar),
                new SqlParameter("@idCard",SqlDbType.VarChar),
                new SqlParameter("@dateOfBirth",SqlDbType.DateTime),
                new SqlParameter("@phoneNumber",SqlDbType.VarChar),
                new SqlParameter("@staffAddress",SqlDbType.VarChar),
                new SqlParameter("@eMail",SqlDbType.VarChar),
                new SqlParameter("@entryDate",SqlDbType.DateTime),
                new SqlParameter("@departureDate",SqlDbType.DateTime),
                new SqlParameter("@operatorOrNot",SqlDbType.Bit),
                new SqlParameter("@staffPicture",SqlDbType.VarChar),
                new SqlParameter("@note",SqlDbType.VarChar),
                new SqlParameter("@staffID",SqlDbType.Int),
            };
            parm[0].Value = "btn_Affirm_Click_UpdateStaff";
            parm[1].Value = as_EmployeeTypeID;
            parm[2].Value = as_WorkStatusID;
            parm[3].Value = as_BranchID;
            parm[4].Value = staffName;
            parm[5].Value = staffNumber;
            parm[6].Value = as_GenderID;
            parm[7].Value = staffAge;
            parm[8].Value = idCard;
            parm[9].Value = dateOfBirth;
            parm[10].Value = phoneNumber;
            parm[11].Value = staffAddress;
            parm[12].Value = eMail;
            parm[13].Value = entryDate;
            parm[14].Value = departureDate;
            parm[15].Value = operatorOrNot;
            parm[16].Value = strPatientPhotos;
            parm[17].Value = note;
            parm[18].Value = staffID;
            return myDAL.UpdateData("UCStaffInformation", parm);
        }
        /// <summary>
        /// 把图片文件保存，返回文件名称
        /// </summary>
        /// <param name="byteTuPian">图片文件</param>
        /// <param name="strOldLuJing">旧路径</param>
        /// <param name="strTxtLuJing">新路径</param>
        /// <returns></returns>
        public string UWenJianLiuZhuanHuanLuJing(byte[][] byteTuPian,string strOldLuJing,string strTxtLuJing)
        {
            string strNewLuJing = "";
            try
            {
                //获取当前的基目录
                string strPath = AppDomain.CurrentDomain.BaseDirectory + "image\\";
                //第一步：判断文件夹是否存在
                if (!Directory.Exists(strPath))
                {
                    //路径不存在：创建文件路径
                    Directory.CreateDirectory(strPath);
                }
                //第二步：分析可能性
                /*
                 思路：分析不同情况
                  （1）新增没选图片OldLuJing=""，现在没选图片byteTuPian=""：不做操作
                  （2）新增没选图片OldLuJing=""，现在选了图片byteTuPian!=""：新增文件               
                  （3）新增选了图片，现在清空图片：删除文件
                  （4）新增选了图片，现在选了图片：替换文件(操作-》删除新增图片，添加现在图片)
               */
                //第一层判断：新增有没有选择图片
                if (strOldLuJing == string.Empty)
                {
                    //新增没有
                    //第二层判断：现在有没有选择图片      
                    if (byteTuPian.Length != 0 && strTxtLuJing != string.Empty)
                    {
                        //现在有:添加现在图片
                        //走情况（2）新增没选图片OldLuJing=""，现在选了图片byteTuPian!=""：新增文件 
                        strNewLuJing = WenJianLiuZhuanHuanLuJing(byteTuPian);
                    }
                }
                else
                {
                    //新增有
                    //第二层判断：现在有没有选择图片
                    if (byteTuPian.Length == 0 && strTxtLuJing == string.Empty)
                    {
                        // 现在没有：删除新增文件
                        //情况（3）新增选了图片，现在清空图片：删除文件
                        //获取原来的图片
                        string strOldUrl = strPath + strOldLuJing;
                        //删除文件
                        System.IO.File.Delete(strOldUrl);
                    }else if (byteTuPian.Length != 0 && strTxtLuJing != string.Empty)
                    {
                        //现在有：替换文件
                        //对应（4）新增选了图片，现在选了图片：替换文件(操作 -》删除新增图片，添加现在图片)
                        //获取原来的图片
                        string strOldUrl = strPath + strOldLuJing;
                        //删除文件(删除指定的文件)
                        System.IO.File.Delete(strOldUrl);
                        //保存现在新的图片
                        strNewLuJing = WenJianLiuZhuanHuanLuJing(byteTuPian);
                    }
                    else if(strOldLuJing== strTxtLuJing)
                    {
                        //没做修改直接保存
                        strNewLuJing = strOldLuJing;
                    }
                }
                return strNewLuJing;

            }
            catch (Exception)
            {
                return null;
            }
        }
        #region
        /// <summary>
        /// 删除员工信息
        /// </summary>
        /// <param name="staffID">员工ID</param>
        /// <param name="strFileName">文件名称</param>
        /// <returns></returns>
        [OperationContract]
        public int DeleteStaffInformation(int staffID,string strFileName)
        {
            if (strFileName !=null)
            {
                DeleteFilePicture(strFileName);
            }
            SqlParameter[] parm =
            {
                new SqlParameter("@type",SqlDbType.VarChar),
                new SqlParameter("@staffID",SqlDbType.VarChar)
            };
            parm[0].Value = "btn_Delete_Click_DelectStaff";
            parm[1].Value = staffID;
            return myDAL.UpdateData("UCStaffInformation", parm);
        }
        /// <summary>
        /// 删除图片
        /// </summary>
        /// <param name="strFileName"></param>
        public void DeleteFilePicture(string strFileNames)
        {
            try
            {
                string strPath = AppDomain.CurrentDomain.BaseDirectory + "image\\";
                //第一步：判断文件夹是否存在
                if (Directory.Exists(strPath))
                {
                    //路径不存在：创建文件路径
                    //Directory.CreateDirectory(strPath);

                    if (strFileNames != string.Empty)
                    {
                        //获取图片
                        string strOldUrl = strPath + strFileNames;
                        //删除指定的文件
                        File.Delete(strOldUrl);
                    }
                }
                


            }
            catch (Exception)
            {
                throw;
            }
        }
        #endregion
    }
}
